package com.nec.recommend.config.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * 数字值转换
 * @author songkaikai
 * @since 2022/7/18
 */
public class NumberJsonSerializer {

    private NumberJsonSerializer() {}

    /**
     * 大数字转换
     */
    public static class BigNumberJsonSerializer extends JsonSerializer<Object> {
        /**
         * 最大值为 Math.pow(2, 53)，十进制为：9007199254740992
         */
        public static final long MAX_NUMBER = 0x20000000000000L;
        /**
         * 最小值为 -Math.pow(2, 53)，十进制为：-9007199254740992
         */
        public static final long MIN_NUMBER = -0x20000000000000L;

        @Override
        public void serialize(Object value, JsonGenerator g, SerializerProvider provider) throws IOException {
            long longValue = ((Number) value).longValue();
            if (longValue < MIN_NUMBER || longValue > MAX_NUMBER) {
                g.writeString(String.valueOf(longValue));
            } else {
                g.writeNumber(longValue);
            }

        }
    }

}
